﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.IO;
using System.Xml.Serialization;
using Dapper_Core.Model;
using Dapper_Core.Model.Dtos;

namespace Dapper_Core.Common.HttpRequests
{
    public class ChinatraceHttpUtility
    {
        private static readonly string Url = "http://api.chinatrace.org/AAQI/v1/ProductData/gtin/";
        private static readonly string GTIN = "/AAQI/v1/ProductData/gtin/[gtin]?targetMarket=156&dataVersion=1.1&clientGln=[clientGln]";
        private static readonly string GLN = "6901234502640";
        private static readonly string Key = "zF3As5ApE7lYpeaABOadZF3CmeTJN/ziMlTked79gb4=";

        /// <summary>
        /// 根据条形码获取商品信息
        /// </summary>
        /// <param name="barcode">条形码号</param>
        public static Result_GetInfoByBarCodeDTO GetInfoByBarCode(string gtin)
        {
            if (gtin.Length < 14)
            {
                gtin = new string('0', 14 - gtin.Length) + gtin;
            }
            string mac = GetMac(gtin);
            string url = $"{Url}{gtin}?targetMarket=156&dataVersion=1.1&clientGln={GLN}&mac={mac}";
            object result = HttpUtility.Get(url, null, null);

            #region 解析xml
            Result_GetInfoByBarCodeDTO productInfo = new Result_GetInfoByBarCodeDTO();
            byte[] bytes = Encoding.Default.GetBytes(result.ToString());
            //根据数据源选择MemoryStream或FileStream
            MemoryStream stream = new MemoryStream(bytes);
            XmlSerializer xmlSearializer = new XmlSerializer(typeof(TSDQueryByGTINResponseType));
            TSDQueryByGTINResponseType info = (TSDQueryByGTINResponseType)xmlSearializer.Deserialize(stream);
            if (info != null && info.productData != null && info.productData.productDataRecord.HasData())
            {
                productInfo.ProductName = info.productData.productDataRecord[0].TSDBasicProductInformationModuleType.productName.Value;
                productInfo.PartyContactName = info.productData.productDataRecord[0].TSDBasicProductInformationModuleType.packagingSignatureLine.partyContactName;
            } 
            #endregion
            return productInfo;
        }

        private static string GetMac(string gtin)
        {
            var key = Key;
            var clientGln = GLN;
            byte[] secretkey = Convert.FromBase64String(key);
            HMACSHA256 provider = new HMACSHA256(secretkey);
            string url = GTIN.Replace("[gtin]", gtin).Replace("[clientGln]", clientGln);
            Encoding ascii = Encoding.ASCII;
            string mac = ByteToHexStr(provider.ComputeHash(ascii.GetBytes(url)));
            return mac;
        }

        private static string ByteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }
    }
}
